import axios from 'axios'
import { Message } from 'element-ui'

import { getToken } from '@/api/auth'

const service = axios.create({
  baseURL: process.env.BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

service.interceptors.request.use(
  config => {
    let token = getToken()
    config.headers['token'] = token
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 20000) {
      Message({
        message: res.msg,
        type: 'error',
        duration: 3 * 1000
      })
      if (res.code === 30000) {
        Message({
          message: '会话超时，请重新登录！',
          type: 'error',
          duration: 3 * 1000
        })
        
        window.location.href = "https://shuttlebus.cuhk.edu.cn"; //登录
      }
      // return Promise.reject('您还未登录或登录信息已失效')
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    // return Promise.reject(error)
  }
)

export default service
